/*
 * @Description:
 * @Author: maxyang
 * @Date: 2022-05-17 09:58:55
 * @LastEditTime: 2022-06-05 22:17:22
 * @LastEditors: liutq
 * @Reference:
 */
/*
 * @Description:
 * @Author: maxyang
 * @Date: 2022-05-17 09:58:55
 * @LastEditTime: 2022-05-17 10:39:37
 * @LastEditors: liutq
 * @Reference:
 */
package model

import (
	"log"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"gopkg.in/ini.v1"
)

var Db *gorm.DB

func InitDB(conf *ini.File) *gorm.DB {
	var err error

	// 数据库的类型
	dbType := conf.Section("").Key("db_type").String()

	// Mysql配置信息
	mysqlName := conf.Section("mysql").Key("db_name").String()
	mysqlUser := conf.Section("mysql").Key("db_user").String()
	mysqlPwd := conf.Section("mysql").Key("db_pwd").String()
	mysqlHost := conf.Section("mysql").Key("db_host").String()
	mysqlPort := conf.Section("mysql").Key("db_port").String()
	mysqlCharset := conf.Section("mysql").Key("db_charset").String()

	dataSource := mysqlUser + ":" + mysqlPwd + "@tcp(" + mysqlHost + ":" +
		mysqlPort + ")/" + mysqlName + "?charset=" + mysqlCharset + "&parseTime=true&loc=Local"

	Db, err = gorm.Open(dbType, dataSource)

	Db.LogMode(true)

	if err != nil {
		Db.Close()
		log.Fatal("数据库连接错误", err)
	}

	// 设置连接池，空闲连接
	Db.DB().SetMaxIdleConns(50)
	// 打开链接
	Db.DB().SetMaxOpenConns(100)

	// 表明禁用后缀加s
	Db.SingularTable(true)

	return Db
}
